﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

/// <summary>
/// Summary description for Helper
/// </summary>
public class Helper
{
	public Helper()
	{
		//
		// TODO: Add constructor logic here
		//
	}
    public static string ResolveUrl(string relativeUrl)
    {
        if (relativeUrl == null) throw new ArgumentNullException("relativeUrl");

        if (relativeUrl.Length == 0 || relativeUrl[0] == '/' || relativeUrl[0] == '\\')
            return relativeUrl;

        int idxOfScheme = relativeUrl.IndexOf(@"://", StringComparison.Ordinal);
        if (idxOfScheme != -1)
        {
            int idxOfQM = relativeUrl.IndexOf('?');
            if (idxOfQM == -1 || idxOfQM > idxOfScheme) return relativeUrl;
        }

        StringBuilder sbUrl = new StringBuilder();
        sbUrl.Append(HttpRuntime.AppDomainAppVirtualPath);
        if (sbUrl.Length == 0 || sbUrl[sbUrl.Length - 1] != '/') sbUrl.Append('/');

        // found question mark already? query string, do not touch!
        bool foundQM = false;
        bool foundSlash; // the latest char was a slash?
        if (relativeUrl.Length > 1
            && relativeUrl[0] == '~'
            && (relativeUrl[1] == '/' || relativeUrl[1] == '\\'))
        {
            relativeUrl = relativeUrl.Substring(2);
            foundSlash = true;
        }
        else foundSlash = false;
        foreach (char c in relativeUrl)
        {
            if (!foundQM)
            {
                if (c == '?') foundQM = true;
                else
                {
                    if (c == '/' || c == '\\')
                    {
                        if (foundSlash) continue;
                        else
                        {
                            sbUrl.Append('/');
                            foundSlash = true;
                            continue;
                        }
                    }
                    else if (foundSlash) foundSlash = false;
                }
            }
            sbUrl.Append(c);
        }

        return sbUrl.ToString();
    }

    public static string Base64Encode(string plainText)
    {
        var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
        return System.Convert.ToBase64String(plainTextBytes);
    }

    public static string Base64Decode(string base64EncodedData)
    {
        var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
        return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
    }
}